package com.jiuyi.service.Impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jiuyi.common.R;
import com.jiuyi.component.RedisCache;
import com.jiuyi.dto.UserPhoneCodeDto;
import com.jiuyi.entity.User;
import com.jiuyi.exception.SystemException;
import com.jiuyi.mapper.UserMapper;
import com.jiuyi.service.UserService;
import com.jiuyi.utils.ValidateCodeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;


import static com.jiuyi.emum.HttpMsgMenu.*;

/**
 * DATA: 2022/10/22
 * Author: 晨夕
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisCache redisCache;

    //获取短信
    @Override
    public R sendMsg(UserPhoneCodeDto userPhoneCodeDto,HttpServletRequest request) {
        //1. 获取手机号，对手机号是否为空进行判断
        if(StringUtils.isEmpty(userPhoneCodeDto.getPhone())){
            throw new SystemException(PHONE_IS_NULL);
        }
        //2. 生成验证码
        Integer code = ValidateCodeUtils.generateValidateCode(4);
//        Integer code = 1024;
        //将验证码存放到redis中
        redisCache.setCacheObject("code",code);
        //设置过期时间
        redisCache.expire("code",60);
        //3. 调用阿里云提供的短信服务
//        SendSms.sendMessage(userPhoneCodeDto.getPhone(),code.toString());
//        System.out.println("手机验证码:" + code);
        return R.ok(code);
    }
    //登录
    @Override
    public R login(UserPhoneCodeDto userPhoneCodeDto, HttpServletRequest request) {
        //1、获取手机号
        String phone = userPhoneCodeDto.getPhone();
        //2、获取验证码，没填写验证码提醒
        String newCode = userPhoneCodeDto.getCode();
        if(StringUtils.isEmpty(newCode)){
            throw new SystemException(CODE_IS_NULL);
        }
        //3. 从redis中获取验证码
        Integer code = redisCache.getCacheObject("code");
        //4、进行验证码对比，验证码不一样提醒
        if(!newCode.equals(code.toString())){
            throw new SystemException(CODE_IS_NOTSAME);
        }
        //5、验证码一样就登录成功，老用户直接登录，新用户直接自动注册
        User user = userMapper.selectByPhone(phone);
        if(ObjectUtils.isEmpty(user)){
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userMapper.insert(user);
        }
        request.getSession().setAttribute("user",user.getId());
        return R.success("登录成功");
    }
    //退出登录
    @Override
    public R logout(HttpServletRequest request) {
        //移除session
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
}
